package game;

public class Board {
	public Board() {	//  Y  X
		board = new int[20][20];
	}
	
	public int[][] getBoard() {
		return board;
	}
	
	public void addBlock(Block block) {
		for( int i = 0; i < block.getBlock().getHeight(); i++ ) {
			for( int j = 0; j < block.getBlock().getWidth(); j++ ) {
				if( block.getBlock().getFrame()[i][j] != 0 )
					board[block.getY()+i][block.getX()+j] = block.getBlock().getFrame()[i][j];
			}
		}
	}
	
	public void fallBlock(Block block) {
		while( fits(block,block.getX(),block.getY()+1) ) {
			block.setPos(block.getX(), block.getY()+1);
		}
		
		addBlock(block);
	}
	
	public boolean fits(Block block) {
		return fits(block, block.getX(), block.getY());
	}
	
	public boolean fits(Block block, int x, int y) {
		if( y < 0 || y > 20-block.getBlock().getHeight() )
			return false;

		for( int i = 0; i < block.getBlock().getHeight(); i++ ) {
			for( int j = 0; j < block.getBlock().getWidth(); j++ ) {
				if(x+j >= 0 && y+i >= 0 && board[y+i][x+j] != 0 && block.getBlock().getAt(i, j) != 0 )
					return false;
			}
		}
		
		return true;
	}
	
	public boolean check() {
		int rec = 0;
		for( int i = 0; i < 20; i++ ) {
			boolean all = true;
			for( int j = 0; j < 10; j++ ) {
				if( board[i][j] == 0 ) {
					all = false;
					break;
				}
			}

			if( all == true) {
				rec++;
				delete( i );
			}
		}
		
		if( rec == 0 )
			return true;
		
		return false;
	}
	
	public void delete( int row ) {
		int[][] newBoard = new int[board.length][board[0].length];
		for( int i = 0; i < newBoard[0].length; i++ )
			newBoard[0][i] = 0;
		
		for( int i = 0; i < row; i++ ) {
			System.arraycopy(board[i], 0, newBoard[i+1], 0, board[i].length);
		}
		
		for( int i = row + 1; i < board.length; i++) {
			System.arraycopy(board[i], 0, newBoard[i], 0, board[i].length);
		}
		
		board = newBoard;
	}
	
	int[][] board;
}
